package com.qiantu.phone.ui.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.toast.ToastUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AreaBean;
import com.qiantu.phone.utils.AddressDataUtil;
import com.lxj.xpopup.core.BottomPopupView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class BottomDistrictDialog extends BottomPopupView {

    private DialogClickListener mDialogClickListener;
    private TextView tvLabel;
    private TextView tvSelectedTime;
    private WheelView wv_first;
    private WheelView wv_second;
    private WheelView wv_third;
    private ArrayWheelAdapter mFirstArrayWheelAdapter;
    private ArrayWheelAdapter mSecondArrayWheelAdapter;
    private ArrayWheelAdapter mThirdArrayWheelAdapter;
    private List<AreaBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AreaBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AreaBean>>> options3Items = new ArrayList<>();
    private AddressDataUtil mAddressDataUtil;
    private String province;
    private String city;
    private String district;

    public BottomDistrictDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_wheel_view;
    }

    // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
    @Override
    protected void onCreate() {
        super.onCreate();
        mAddressDataUtil = new AddressDataUtil();
        tvLabel = findViewById(R.id.tv_label);
        tvSelectedTime = findViewById(R.id.tv_selected_time);
        wv_first = findViewById(R.id.options1);
        wv_second = findViewById(R.id.options2);
        wv_third = findViewById(R.id.options3);
        LinearLayout wheelViewContainer = findViewById(R.id.wheel_view_container);
        LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) wheelViewContainer.getLayoutParams();
        ll.rightMargin = getResources().getDimensionPixelSize(R.dimen.dp_16);
        ll.leftMargin = getResources().getDimensionPixelSize(R.dimen.dp_16);
        View btnSave = findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mDialogClickListener != null){
                    mDialogClickListener.onConfirmClick(tvSelectedTime.getText().toString(), tvSelectedTime.getTag().toString());
                }
            }
        });
        tvLabel.setText("地区选择");
        setStyle();
        initWheelView();
        initJsonData();
    }

    private void setStyle() {
        wv_first.setGravity(Gravity.CENTER);
        wv_first.setCyclic(false);
        wv_first.setAlphaGradient(true);
//        wv_first.setLabelOffset(5);
        wv_first.setItemsVisibleCount(5);
        wv_first.setDividerColor(0x00000000);
        wv_first.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_first.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_second.setGravity(Gravity.CENTER);
        wv_second.setCyclic(false);
        wv_second.setAlphaGradient(true);
//        wv_second.setLabelOffset(5);
        wv_second.setItemsVisibleCount(5);
        wv_second.setDividerColor(0x00000000);
        wv_second.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_second.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_third.setGravity(Gravity.CENTER);
        wv_third.setCyclic(false);
        wv_third.setAlphaGradient(true);
//        wv_third.setLabelOffset(5);
        wv_third.setItemsVisibleCount(5);
        wv_third.setDividerColor(0x00000000);
        wv_third.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_third.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));
    }

    private void initJsonData() {//解析数据
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                String jsonData = mAddressDataUtil.getAddressJson(getContext());
                Gson gson = new Gson();
                Type listType = new TypeToken<List<AreaBean>>() {}.getType();
                ArrayList<AreaBean> province = gson.fromJson(jsonData, listType);//用Gson 转成实体
                //添加省份数据
                options1Items = province;
                for (int i = 0; i < province.size(); i++) {//遍历省份
                    ArrayList<AreaBean> cityList = new ArrayList<>();//该省的城市列表（第二级）
                    ArrayList<ArrayList<AreaBean>> city_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
                    for (int c = 0; c < province.get(i).getChilds().size(); c++) {//遍历该省份的所有城市
                        AreaBean city = province.get(i).getChilds().get(c);
                        cityList.add(city);//添加城市
                        ArrayList<AreaBean> areaList = new ArrayList<>();//该城市的所有地区列表
                        areaList.addAll(province.get(i).getChilds().get(c).getChilds());
                        city_AreaList.add(areaList);//添加该省所有地区数据
                    }
                    //添加城市数据
                    options2Items.add(cityList);
                    //添加地区数据
                    options3Items.add(city_AreaList);
                }
                emitter.onNext(true);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean result) throws Exception {
                        setData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(R.string.load_area_data_failed);
                    }
                });
    }

    private void initWheelView(){
        //先设置空列表，不然WheelView不会测量宽高
        mFirstArrayWheelAdapter = new ArrayWheelAdapter(options1Items);
        wv_first.setAdapter(mFirstArrayWheelAdapter);

        mSecondArrayWheelAdapter = new ArrayWheelAdapter(options1Items);
        wv_second.setAdapter(mSecondArrayWheelAdapter);

        mThirdArrayWheelAdapter = new ArrayWheelAdapter(options1Items);
        wv_third.setAdapter(mThirdArrayWheelAdapter);
        wv_first.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                if(options2Items.size() > 0){
                    mSecondArrayWheelAdapter = new ArrayWheelAdapter(options2Items.get(index));
                    wv_second.setAdapter(mSecondArrayWheelAdapter);
                    wv_second.setCurrentItem(0);
                }

                if(options3Items.size() > 0){
                    mThirdArrayWheelAdapter = new ArrayWheelAdapter(options3Items.get(index).get(0));
                    wv_third.setAdapter(mThirdArrayWheelAdapter);
                    wv_third.setCurrentItem(0);
                }

                setSelected();
            }
        });
        wv_second.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                if(options3Items.size() > 0){
                    ArrayList<ArrayList<AreaBean>> list = options3Items.get(wv_first.getCurrentItem());
                    if(index < list.size()){
                        mThirdArrayWheelAdapter = new ArrayWheelAdapter(list.get(index));
                        wv_third.setAdapter(mThirdArrayWheelAdapter);
                        wv_third.setCurrentItem(0);
                        setSelected();
                    }
                }
            }
        });
        wv_third.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                setSelected();
            }
        });
    }

    private void setData(){
        mFirstArrayWheelAdapter = new ArrayWheelAdapter(options1Items);
        wv_first.setAdapter(mFirstArrayWheelAdapter);
        setSelectedItem(province, city, district);

        if(options2Items.size() > 0){
            mSecondArrayWheelAdapter = new ArrayWheelAdapter(options2Items.get(wv_first.getCurrentItem()));
            wv_second.setAdapter(mSecondArrayWheelAdapter);
        }

        if(options3Items.size() > 0){
            mThirdArrayWheelAdapter = new ArrayWheelAdapter(options3Items.get(wv_first.getCurrentItem()).get(wv_second.getCurrentItem()));
            wv_third.setAdapter(mThirdArrayWheelAdapter);
        }
        setSelected();
    }

    private void setSelected(){
        AreaBean firstItem = (AreaBean) wv_first.getAdapter().getItem(wv_first.getCurrentItem());
        AreaBean secondItem = (AreaBean) wv_second.getAdapter().getItem(wv_second.getCurrentItem());
        AreaBean thirdItem = (AreaBean) wv_third.getAdapter().getItem(wv_third.getCurrentItem());
        String name = firstItem.getName() + " " + secondItem.getName() + " " + thirdItem.getName();
        tvSelectedTime.setText(name);
        tvSelectedTime.setTag(thirdItem.getCode());
    }

    public void setSelectedItem(String province, String city, String district){
        this.province = province;
        this.city = city;
        this.district = district;
        if(wv_first == null || wv_second == null || wv_third == null){
            return;
        }
        int item1=10;
        int item2=1;
        int item3=4;
        if(TextUtils.isEmpty(this.province) && TextUtils.isEmpty(this.city) && TextUtils.isEmpty(this.district)){
            wv_first.setCurrentItem(item1);
            wv_second.setCurrentItem(item2);
            wv_third.setCurrentItem(item3);
        }else {
            if (options1Items != null && options1Items.size() > 0) {
                for (int i = 0; i < options1Items.size(); i++) {
                    AreaBean area = options1Items.get(i);
                    if (area.getName().equals(province)) {
                        item1 = i;
                        wv_first.setCurrentItem(item1);
                        break;
                    }
                }
            }

            if (options2Items != null && options2Items.size() > 0) {
                for (int i = 0; i < options2Items.size(); i++) {
                    AreaBean area = options2Items.get(item1).get(i);
                    if (area.getName().equals(city)) {
                        item2 = i;
                        wv_second.setCurrentItem(item2);
                        break;
                    }
                }
            }

            if (options3Items != null && options3Items.size() > 0) {
                for (int i = 0; i < options3Items.size(); i++) {
                    AreaBean area = options3Items.get(item1).get(item2).get(i);
                    if (area.getName().equals(district)) {
                        item3 = i;
                        wv_third.setCurrentItem(item3);
                        break;
                    }
                }
            }
        }
    }

    // 设置最大宽度，看需要而定
    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }

    // 设置最大高度，看需要而定
    @Override
    protected int getMaxHeight() {
        return super.getMaxHeight();
    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return 0;
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return 0;
    }

    public void setDialogClickListener(@Nullable DialogClickListener listener) {
        mDialogClickListener = listener;
    }

    public interface DialogClickListener {
        void onConfirmClick(String name, String code);
    }
}
